package com.joelaws.prototype.server.blackberry;

import java.io.File;

import org.restlet.Context;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.FileRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import com.joelaws.prototype.client.data.User;
import com.joelaws.prototype.server.dao.DAOFactory;

public class UserPicture extends Resource {

	private static final String PICTURE_PATH = "/var/lib/tomcat-6/webapps/JPEntertainment/";

	private long userID;

	public UserPicture(Context context, Request request, Response response) {
		super(context, request, response);

		String[] data = request.getResourceRef().getRemainingPart().split("=");
		if (data != null && data.length == 2)
			userID = Long.parseLong(data[1]);
		else
			userID = Long.MIN_VALUE;
		super.getVariants().add(new Variant(MediaType.IMAGE_JPEG));
	}

	@Override
	public Representation getRepresentation(Variant variant) {
		if (userID == Long.MIN_VALUE)
			return new StringRepresentation("Invalid userID",
					MediaType.TEXT_PLAIN);

		User user = DAOFactory.getUserDAO().getUser(userID);
		if (user == null || user.getNetworkingService() == null
				|| user.getNetworkingService().getPicture() == null) {
			return new StringRepresentation("Invalid user",
					MediaType.TEXT_PLAIN);
		}

		String path = PICTURE_PATH
				+ user.getNetworkingService().getPicture().getLocation();
		if (!(new File(path).exists())) {
			return new StringRepresentation("No picture for user " + path,
					MediaType.TEXT_PLAIN);
		}

		return new FileRepresentation(path, MediaType.IMAGE_PNG, 10);// IMAGE_JPEG,
		// 10);
	}

	public static String getURL() {
		return "/getPicture";
	}
}
